import { formatThisWithDot, importFromOrigin } from './common.js'

const formatBody = (str, section) => {
  return str
    .split('\n')
    .map((item) => formatThisWithDot(item, section))
    .filter((item) => item)
    .join('\n')
}

export const formatCycle = ({ cycle1, cycle2, cycle3, cycle4, name1, name2, name3, name4, keyword }) => {
  const reg1 = new RegExp(name1 + '\\((.*?)\\)\\s?\\{([\\s\\S]*?)\\s*?\\}$')
  const reg2 = new RegExp(name2 + '\\((.*?)\\)\\s?\\{([\\s\\S]*?)\\s*?\\}$')
  const reg3 = new RegExp(name3 + '\\((.*?)\\)\\s?\\{([\\s\\S]*?)\\s*?\\}$')
  const reg4 = new RegExp(name4 + '\\((.*?)\\)\\s?\\{([\\s\\S]*?)\\s*?\\}$')
  const var1 = cycle1?.replace(reg1, '$2') || ''
  const var2 = cycle2?.replace(reg2, '$2') || ''
  const var3 = cycle3?.replace(reg3, '$2') || ''
  const var4 = cycle4?.replace(reg4, '$2') || ''
  if (var1 || var2 || var3 || var4) {
    const isAsync = var1.search(/await /g) >= 0 || var2.search(/await /g) >= 0 || var3.search(/await /g) >= 0 || var4.search(/await /g) >= 0
    importFromOrigin(keyword)
    return `${keyword}(${isAsync ? 'async ' : ''}() => {
            ${formatBody(var1, name1)}
            ${formatBody(var2, name2)}
            ${formatBody(var3, name3)}
            ${formatBody(var4, name4)}
        })`
  } else {
    return ''
  }
}
